package yaml

import (
	"ez-starter/runner"
	"fmt"
	"gitee.com/dreamwood/ez"
	ym "gopkg.in/yaml.v2"
	"os"
	"strings"
	"time"
)

func PassTo(key string, v interface{}) {
	backToConfig, e := ym.Marshal(v)
	if ez.PrintError(e) {
		return
	}
	switch key {
	case "run":
		md := new(runner.Runner)
		e = ym.Unmarshal(backToConfig, &md)
		if ez.PrintError(e) {
			return
		}
		for index, str := range md.Cmd {
			md.Cmd[index] = Replace(str)
		}
		md.Run()
	}
	return
}

var (
	now      string
	y        string
	m        string
	d        string
	h        string
	i        string
	s        string
	replacer []string
)

func InitVar() {
	cur := time.Now()
	replacer = make([]string, 0)
	now = fmt.Sprintf("%d", cur.Unix())
	y = fmt.Sprintf("%d", cur.Year())
	m = fmt.Sprintf("%02d", cur.Month())
	d = fmt.Sprintf("%02d", cur.Day())
	h = fmt.Sprintf("%02d", cur.Hour())
	i = fmt.Sprintf("%02d", cur.Minute())
	s = fmt.Sprintf("%02d", cur.Second())
	replacer = append(replacer, "$NOW$", now)
	replacer = append(replacer, "$YMD$", y+m+d)
	replacer = append(replacer, "$YMDHIS$", y+m+d+h+i+s)
	replacer = append(replacer, "$YY$", y)
	replacer = append(replacer, "$MM$", m)
	replacer = append(replacer, "$DD$", d)
	replacer = append(replacer, "$HH$", h)
	replacer = append(replacer, "$II$", i)
	replacer = append(replacer, "$SS$", s)
	root, _ := os.Getwd()
	replacer = append(replacer, "$ROOT$", root)
}

func Replace(src string) string {
	r := strings.NewReplacer(replacer...)
	return r.Replace(src)
}
